package org.aeon.client.view.components.textField;

import org.aeon.utils.ImageSetUtil;

import javax.swing.FocusManager;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

/**
 * @author WZH
 */
public class SearchField extends JTextField {
    private final ImageIcon icon;
    private String placeholder;
    private boolean isInput;

    public SearchField(Dimension dimension) {
        icon = new ImageIcon(ImageSetUtil.getImage("search", 25, 25));
        Insets insets = new Insets(0, 30, 0, 5);
        // 设置文本输入距左边20
        this.setMargin(insets);
        this.setPreferredSize(new Dimension(250, 30));
        this.setFont(new Font("黑体", Font.PLAIN, 16));

        this.setPreferredSize(dimension);
        this.setMaximumSize(dimension);
        this.setMinimumSize(dimension);

        this.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                SearchField.this.repaint();
            }

            @Override
            public void focusLost(FocusEvent e) {
                SearchField.this.repaint();
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Insets insets = getInsets();
        super.paintComponent(g);
        int iconWidth = icon.getIconWidth();
        int iconHeight = icon.getIconHeight();
        int Height = this.getHeight();
        // 在文本框中画上之前图片
        icon.paintIcon(this, g, (insets.left - iconWidth) / 2, (Height - iconHeight) / 2);


        if (getText().isEmpty() && !(FocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == this)) {
            Font prevFont = g.getFont();
            Color prevColor = g.getColor();

            // g.setFont(getFont().deriveFont(Font.ITALIC));
            g.setColor(Color.GRAY);
            g.drawString(placeholder, getInsets().left, g.getFontMetrics().getHeight() + getInsets().top);

            g.setFont(prevFont);
            g.setColor(prevColor);
        }
    }

    public void addDocumentListenerHandle(Runnable handle) {
        this.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                handle.run();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                handle.run();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                handle.run();
            }
        });
    }

    public void setPlaceholder(String placeholder) {
        this.placeholder = placeholder;
        this.repaint();
    }
}
